package org.example.backend.demos.web.ImageModule.service.impl;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;

@Service
public class CosServise {


    @Autowired
    private TransferManager transferManager;

    @Autowired
    private COSClient cosClient;


    // 上传文件
    public String upfile(MultipartFile file) {

        String bucketName = "mydata-1371258874";
        String key = "user/" + file.getOriginalFilename();
        String SRC = "";
        try {
            // 使用 InputStream 方式上传
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(), metadata);
            Upload upload = transferManager.upload(putObjectRequest);
            UploadResult uploadResult = upload.waitForUploadResult();
            SRC = uploadResult.getDateStr();
            System.out.println(uploadResult.getDateStr());
            System.out.println(uploadResult.getCiUploadResult());
            System.out.println(uploadResult.getBucketName());
            System.out.println(uploadResult.getETag());
            System.out.println(uploadResult.getCrc64Ecma());
            System.out.println(uploadResult.getKey());
            System.out.println(uploadResult.getRequestId());
            System.out.println(uploadResult.getVersionId());
        } catch (Exception e) {
            e.printStackTrace();
            return "文件处理失败: " + e.getMessage();

        }
        return SRC;
    }
    // 下载文件
    public String downfile() throws InterruptedException {
        String bucketName = "mydata-1371258874";
        String key = "user/屏幕截图 2025-10-16 214901.png";

        // 检查依赖是否已注入
        if (cosClient == null) {
            throw new IllegalStateException("COS客户端未初始化");
        }

        if (transferManager == null) {
            throw new IllegalStateException("TransferManager未初始化");
        }

        // 检查文件是否存在
        ObjectMetadata objectMetadata = cosClient.getObjectMetadata(bucketName, key);
        System.out.println("文件存在，开始下载...");
        String localFilePath = "屏幕截图 2025-10-16 214901.png";
        File downloadFile = new File(localFilePath);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        Download download = transferManager.download(getObjectRequest, downloadFile);
        download.waitForCompletion();
        return download.getBucketName();

    }


}
